package dao

import (
	"gorm.io/gorm"
	"myserver/model"
	"myserver/param"
	"myserver/tool"
)

type SubsidyDao struct {
	*tool.MyOrm
}

func (d *SubsidyDao) GetSubsidy(m *model.Subsidy) *gorm.DB {
	res := d.Db.First(&m)
	return res
}

func (d *SubsidyDao) CreateSubsidy(subsidy model.Subsidy) int64 {
	res := d.Db.Create(&subsidy)
	return res.RowsAffected
}

func (d *SubsidyDao) DeleteSubsidy(subsidy model.Subsidy) int64 {
	res := d.Db.Delete(&subsidy)
	return res.RowsAffected
}

func (d *SubsidyDao) UpdateSubsidy(subsidy model.Subsidy) int64 {
	res := d.Db.Updates(&subsidy)
	return res.RowsAffected
}

func (d *SubsidyDao) QuerySubsidy(pageParam param.PageParam) param.ResponsePageParam {
	rs := param.ResponsePageParam{}
	rs.Data = []model.Subsidy{}
	db := d.Db.Model(&model.Subsidy{})
	if pageParam.SearchContent != "" {
		db = db.Where("subsidy_name LIKE ?", "%"+pageParam.SearchContent+"%")
	}
	db.Order("ID ASC").Count(&rs.Total).Limit(pageParam.Limit).Offset(pageParam.Page).Find(&rs.Data)
	return rs
}

func (d *SubsidyDao) GetRsSubsidy(subsidy model.Subsidy) int64 {
	db := d.Db
	var count int64
	db.Raw("SELECT subsidy_id FROM user_subsidy WHERE subsidy_id = ?", subsidy.ID).Distinct("user_id", "subsidy_id").Count(&count)
	return count
}

func (d *SubsidyDao) CreateRsSubsidy(reservation model.Reservation) int64 {
	db := d.Db
	res := db.Exec("INSERT INTO user_subsidy VALUES (?, ?)", reservation.UserID, reservation.ResourceID)
	return res.RowsAffected
}

func (d *SubsidyDao) UserSubsidys(pageParam param.PageParam) param.ResponsePageParam {
	rs := param.ResponsePageParam{}
	rs.Data = []model.Subsidy{}
	db := d.Db
	db.Table("users").Select("subsidies.subsidy_name, subsidies.id, subsidies.money, subsidies.amount, subsidies.describe, subsidies.subsidies_image").Joins("left join user_subsidy on user_subsidy.user_id = users.id and users.id = ?", pageParam.UserId).Joins(
		"left join subsidies on user_subsidy.subsidy_id = subsidies.id and subsidies.id is not null").Where("user_id = ?", pageParam.UserId).Order("ID desc").Count(&rs.Total).Limit(pageParam.Limit).Offset(pageParam.Page).Find(&rs.Data)
	return rs
}
